package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.commom.exception.CustException;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.behavior.pojo.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author by jojo
 * @Date 2022/3/8
 * @Description
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 记录阅读行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
//        1. 校验参数 文章id必须传
        ApUser apUser = AppThreadLocalUtils.getUser();
//        2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        Integer equipmentId = dto.getEquipmentId();
        Integer userId = apUser.getId();
        if (userId==null&&equipmentId==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"不能既不登录又不给设备id");
        }
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), equipmentId);
//        3. 判断阅读行为是否存在
        String entryId = apBehaviorEntry.getId();
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(entryId));
        ApReadBehavior one = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (one==null) {
           // 4. 不存在  创建阅读行为 并初始化count字段值为1
            ApReadBehavior apReadBehavior = new ApReadBehavior();
            apReadBehavior.setEntryId(entryId);
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            apReadBehavior.setCount((short)1);
            mongoTemplate.save(apReadBehavior);
        }else {
            // 5. 存在  将阅读行为的count字段加1 并修改
            Short count = one.getCount();
            Short i=1;
            Update update = new Update();
            update.set("count",(short)(count+i)).set("updatedTime",new Date());
            mongoTemplate.updateFirst(query,update,ApReadBehavior.class);
        }
        NewBehaviorDTO messDto = new NewBehaviorDTO();
        messDto.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        messDto.setArticleId(dto.getArticleId());
        messDto.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(messDto));
        log.info("阅读行为发送MQ消息成功  ==》参数={}",messDto);
        return ResponseResult.okResult();
    }
}
